﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CLFramework.Infrastructure.Validation
{
    public class ValidationState
    {
        public ValidationState()
        {
            Errors = new ValidationErrorCollection();
        }

        public ValidationState(IEnumerable<ValidationError> errors)
        {
            if (errors != null)
                foreach (ValidationError error in errors)
                    Errors.Add(error);
        }

        public ValidationErrorCollection Errors { get; private set; }

        public bool IsValid
        {
            get
            {
                return Errors.Count == 0;
            }
        }

        public void AddValidationError(object attemptedValue, string name, Exception exception)
        {
            ValidationError error = new ValidationError(name, attemptedValue, exception);
            this.Errors.Add(error);
        }

        public void AddValidationError(object value, string validationKey, string validationMessageKey
            , string validationMessage, params object[] validationMessageParameters)
        {
            if (validationMessageParameters != null && validationMessageParameters.Length > 0)
                validationMessage = string.Format(validationMessage, validationMessageParameters);

            ValidationError error = new ValidationError(
                validationKey,
                value,
                new InvalidOperationException(validationMessage)
                );
            this.Errors.Add(error);
        }

        public void Merge(ValidationState state)
        {
            this.Errors.AddRange(state.Errors);
        }
    }

}
